from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.user import User as UserModel, UserInDB
from app.schemas.user import User as UserSchema, UserCreate, UserUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from app.utils.jwt import get_password_hash
from datetime import datetime

router: APIRouter = APIRouter(prefix="/users", tags=["用户管理"])

@router.post("/create", response_model=APIResponse[UserSchema])
def create_user(user: UserCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating user with username: {user.username}")
    
    # 检查用户名是否已存在
    db_user = db.query(UserModel).filter(UserModel.username == user.username).first()
    if db_user:
        logger.warning(f"Username already registered: {user.username}")
        return error_response(message="Username already registered", code=400)
    
    # 创建新用户
    # 对密码进行哈希处理
    password_hash = get_password_hash(user.password)
    
    db_user = UserModel(
        username=user.username,
        password=password_hash,
        real_name=user.real_name,
        phone=user.phone,
        email=user.email,
        status=user.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    # 转换为Pydantic模型
    user_response = UserInDB.model_validate(db_user)
    
    logger.info(f"User created successfully with ID: {db_user.id}")
    return success_response(data=user_response, message="User created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[UserSchema]])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching users with skip: {skip}, limit: {limit}")
    
    users = db.query(UserModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    users_response = [UserInDB.model_validate(user) for user in users]
    total = db.query(UserModel).count()
    
    logger.info(f"Found {len(users)} users")
    return paginated_response(
        items=users_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{user_id}", response_model=APIResponse[UserSchema])
def read_user(user_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching user with ID: {user_id}")
    
    db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if db_user is None:
        logger.warning(f"User not found with ID: {user_id}")
        return error_response(message="User not found", code=404)
    
    # 转换为Pydantic模型
    user_response = UserInDB.model_validate(db_user)
    
    logger.info(f"User found with ID: {user_id}")
    return success_response(data=user_response)

@router.put("/{user_id}", response_model=APIResponse[UserSchema])
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating user with ID: {user_id}")
    
    db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if db_user is None:
        logger.warning(f"User not found with ID: {user_id}")
        return error_response(message="User not found", code=404)
    
    # 更新用户信息
    update_data = user.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_user, key, value)
    
    setattr(db_user, 'update_time', datetime.utcnow())
    db.commit()
    db.refresh(db_user)
    
    # 转换为Pydantic模型
    user_response = UserInDB.model_validate(db_user)
    
    logger.info(f"User updated successfully with ID: {user_id}")
    return success_response(data=user_response, message="User updated successfully")

@router.delete("/{user_id}", response_model=APIResponse[None])
def delete_user(user_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting user with ID: {user_id}")
    
    db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
    if db_user is None:
        logger.warning(f"User not found with ID: {user_id}")
        return error_response(message="User not found", code=404)
    
    db.delete(db_user)
    db.commit()
    
    logger.info(f"User deleted successfully with ID: {user_id}")
    return success_response(message="User deleted successfully")